<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/8/25
 * Time: 14:12
 */

namespace Shop\Http\Controllers\Wap;

use App\Helpers\SelfResponse;
use Frontend\Models\UserBaseModel;
use Illuminate\Http\Request;
use Shop\Http\Controllers\BaseController;
use App\Models\Shop\UpgradeModel;
use App\Models\Shop\UpgradeInfoModel;

class UpgradeController extends BaseController{

    public function index(Request $request)
    {

        // 系统 最大级别
        $sys_max_level = config('shop.sys_level');

        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);

        $is_lock = 0;
        if($info->info['weichat'] == '' || $info->info['receiving_code'] ==''){
           $is_lock = 1;
        }

        //比较级别
        if($info['level'] < $sys_max_level){

            $next_level = $info['level'] +1;

            // 判断 当前级别是否 申请过
            $level_count_map = [
                'status'=>1,
                'user_id'=>$user_id,
                'up_before_level'=>$info['level'],
                'up_after_level'=>$next_level
            ];
            $level_count = UpgradeModel::init()->where($level_count_map)->first();
        }

        return $this->wapRender('upgrade.index',[
            'page_title'=>'升级',
            'info'=>$info,
            'sys_level'=>$sys_max_level,
            'next_level'=>$next_level ?? 0,
            'level_count'=>$level_count ?? '',
            'is_lock'=>$is_lock
        ]);

    }

    // 申请升级

    public function apply(Request $request){

        // 系统 最大级别
        $sys_max_level = config('shop.sys_level');

        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);


        if($request->isMethod('post')){

            $next_level = $info['level']+1;

            if($next_level > $sys_max_level){
                return SelfResponse::error('系统升级制度异常！！！');
            }

            // 判断 当前级别是否 申请过
            $level_count_map = [
                'status'=>1,
                'user_id'=>$user_id,
                'up_before_level'=>$info['level'],
                'up_after_level'=>$next_level
            ];
            $level_count = UpgradeModel::init()->where($level_count_map)->first();

            if($level_count){
                return redirect()->route('f_Wap_Upgrade_apply_match_detail',['id'=>$level_count['id']]);
            }

            // 开始 判断 升级

            $referrer_ids = str2arr($info['referrer_ids']);

            if($info['level'] == 0) {

                $one_deep = $info->tdeep  - $next_level;

                if($one_deep <= 0){
                    $one_deep = 0;
                }

                $one_info = UserBaseModel::where('status','>=',0)
                    ->whereIn('member_id',$referrer_ids)
                    ->where('tdeep','<=',$one_deep)
                    ->where('is_out',0)->where(function ($query)use ($next_level){
                        $query->where('level','>=',$next_level)->orWhere('is_active','=',1);
                    })
                    ->orderBy('tdeep','desc')->first();

                if (empty($one_info)) {
                    $one_info = UserBaseModel::with('info')->where('member_id',1)->first();
                }

                $two_deep = $info->tdeep  - $sys_max_level;

                if($two_deep <= 0){
                    $two_deep = 0;
                }

                $two_info = UserBaseModel::where('status','>=',0)
                    ->whereIn('member_id',$referrer_ids)
                    ->where('tdeep','<=',$two_deep)
                    ->where('is_out',0)
                    ->where('level','>=',$sys_max_level)->orderBy('tdeep','desc')->first();

                if (empty($two_info)) {
                    $two_info = UserBaseModel::with('info')->where('member_id',1)->first();
                }

            }else if($info['level'] >0 && $info['level'] < $sys_max_level){

                if($info['level'] == 1){
                    $rec_count = UserBaseModel::where('status','>=',0)->where('referrer_id','=',$user_id)->where('level','>=',1)->orWhere('is_active','=',1)->count();

                    if($rec_count < get_rule('tj_max_deep')){
                        return SelfResponse::error('您不满足升级条件，需要完成'.get_rule('tj_max_deep').'个激活推荐！！！');
                    }
                }

                $one_deep = $info->tdeep  - $next_level;

                if($one_deep <= 0){
                    $one_deep = 0;
                }

                $one_model = UserBaseModel::where('status','>=',0)
                    ->whereIn('member_id',$referrer_ids)
                    ->where('tdeep','<=',$one_deep)
                    ->where('is_out',0)
                    ->where('level','>=',$next_level);

                $one_info = $one_model->with('info')->orderBy('tdeep','desc')->first();

                if (empty($one_info)) {
                    $one_info = UserBaseModel::with('info')->where('member_id',1)->first();
                }
                $two_info = [];
            }else{
                return SelfResponse::error('系统升级制度异常！！！');
            }

            if($two_info){
                $two_hand_uid = $two_info['member_id'];
            }else{
                $two_hand_uid = '';
            }

            $upgrade_data = [
                'user_id'=>$user_id,
                'hand_uids'=>$one_info['member_id'].",".$two_hand_uid,
                'up_before_level'=>$info['level'],
                'up_after_level' =>$next_level,
            ];

            $id = UpgradeModel::init()->createUpgrade($upgrade_data);
            if($id){

                $upgrade_one_data = [
                    'user_id'=>$user_id,
                    'up_before_level'=>$info['level'],
                    'up_after_level' =>$next_level,
                    'hand_uid'=>$one_info['member_id'],
                    'upgrade_id'=>$id
                ];
                $one_id = UpgradeInfoModel::init()->createUpgradeInfo($upgrade_one_data);

                if(!$one_id){
                    UpgradeModel::init()->where('id',$id)->delete();
                    return SelfResponse::error('申请记录添加出错！！！');
                }
                if($two_info){
                    $upgrade_two_data = [
                        'user_id'=>$user_id,
                        'up_before_level'=>$info['level'],
                        'up_after_level' =>$next_level,
                        'hand_uid'=>$two_info['member_id'],
                        'upgrade_id'=>$id
                    ];
                    $two_id = UpgradeInfoModel::init()->createUpgradeInfo($upgrade_two_data);
                    if(!$two_id){
                        UpgradeModel::init()->where('id',$id)->delete();
                        UpgradeInfoModel::init()->where('id',$one_id)->delete();
                        return SelfResponse::error('申请记录添加出错！！！');
                    }
                }
                return SelfResponse::success('申请成功',['f_Wap_Upgrade_apply_match_detail',['id'=>$id]]);
            }else{
                return SelfResponse::error('申请记录添加出错！！！');
            }

        }

    }


    // 申请记录
    public function applyRecord(Request $request){

        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);

        $status = $request->input('status',false);

        $model = UpgradeModel::init()->where('user_id',$user_id);

        if($status !== false){
            $model->where('status',$status);
        }

        $list = $model->forPage($pageNum,$this->perNum())->get();

        return $this->wapRender('upgrade.apply_record',[
            'page_title'=>'申请记录',
            'list'=>$list,
            'status'=>$status,
        ]);

    }

    // 匹配详情
    public function applyMatchDetail(Request $request){

        $user_id = $request->input('user_id');
        $id = $request->input('id');
        $list = UpgradeInfoModel::with('HandUser','HandUserInfo')->where('user_id',$user_id)->where('upgrade_id',$id)->get();

        return $this->wapRender('upgrade.apply_detail',[
            'page_title'=>'匹配信息',
            'list'=>$list,
            'user_id'=>$user_id
        ]);

    }

    // 匹配打款
    public function applyMatchPay(Request $request){
        $user_id = $request->input('user_id');
        $id = $request->input('order_id');
        $pay_info = UpgradeInfoModel::with('HandUser','HandUserInfo')->where('user_id',$user_id)->where('id',$id)->first();

        return $this->wapRender('upgrade.apply_pay',[
            'page_title'=>'匹配打款',
            'pay_info'=>$pay_info,
        ]);
    }

    // 匹配打款
    public function applyMatchSendPay(Request $request){

        if($request->isMethod('post')){
            $user_id = $request->input('user_id');
            $order_id = $request->input('order_id');
            $voucher = $request->input('voucher');
            $remark = $request->input('remark');

            if(UpgradeInfoModel::init()->payOrder($order_id,$user_id,$voucher,$remark)){
                return SelfResponse::success('提交成功','f_Wap_Upgrade_index');
            }
            return SelfResponse::error(UpgradeInfoModel::init()->getErrorMsg('提交失败'));
        }

    }


    // 审核信息

    public function handleRecord(Request $request){

        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);

        $status = $request->input('status',false);

        $model = UpgradeInfoModel::init()->with('ApplyUser','ApplyUserInfo')->where('hand_uid',$user_id);

        if($status !== false){
            $model->where('status',$status);
        }

        $list = $model->forPage($pageNum,$this->perNum())->get();

        return $this->wapRender('upgrade.hand_record',[
            'page_title'=>'审核记录',
            'list'=>$list,
            'status'=>$status,
            'user_id'=>$user_id
        ]);

    }

    // 处理审核
    public function handleApply(Request $request){

        $user_id = $request->input('user_id');

        $order_id = $request->input('order_id');
        $status = $request->input('status');


        $order = UpgradeInfoModel::init()->where('status',1)->where('hand_uid',$user_id)->find($order_id);
        if(!$order){
            return SelfResponse::error('订单不存在') ;
        }

        if(UpgradeInfoModel::init()->handleOrder($order_id,$user_id,$status)){

            return SelfResponse::success('审核成功','f_Wap_Upgrade_handle_record');
        }

        return SelfResponse::error('审核失败');
    }

    // 打款进度
    public function matchSpeed(Request $request){
        $sys_max_level = config('shop.sys_level');

        $user_id = $request->input('user_id');
        $list=[];
        for ($i=1;$i<=$sys_max_level;$i++){
            $list[$i]['sum_money'] = UpgradeInfoModel::init()->where('hand_uid',$user_id)->where('status',2)->where('up_after_level',$i)->sum('pay_money');
            $list[$i]['sum_total'] = UpgradeInfoModel::init()->where('hand_uid',$user_id)->where('status',2)->where('up_after_level',$i)->count();
        }

        return $this->wapRender('upgrade.match_speed',[
            'page_title'=>'打款进度',
            'list'=>$list,
        ]);

    }


}